package top.joeallen.rtmptoflv.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

import top.joeallen.rtmptoflv.service.RtmpToFlvService;
import top.joeallen.rtmptoflv.util.CommandUtil;

/**
 * @author JoeAllen_Li
 * @Date 2021/3/19 16:03
 * @describe
 */
@RestController
public class Rtmp {
    @Resource
    RtmpToFlvService rtmpToFlvService;

    /**
     * 接受rtmp地址并执行转换
     *
     * @param rtmp 地址
     * @return 返回播放
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/rtmp", method = RequestMethod.POST)
    public String rtmp(@RequestParam("rtmp") String rtmp) {
        String to = rtmpToFlvService.queryAll(rtmp).getTo();
        System.out.println("to==" + to);
        if (!ls(to)) {
            ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("thread-call-runner-%d").build();
            ExecutorService service = new ThreadPoolExecutor(5, 999999, 200L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), namedThreadFactory);
            service.execute(() -> {
                try {
                    JSch jsch = new JSch(); // 创建JSch对象
                    String userName = "root";// 用户名
                    String password = "toor";// 密码
                    String host = "127.0.0.1";// 服务器地址
                    int port = 22;// 端口号
                    //String cmd = "cat /data/hello.txt";// 要运行的命令
                    String cmd = "./java/rtmp/rtmp " + rtmp + " " + to;// 要运行的命令
                    Session session; // 根据用户名，主机ip，端口获取一个Session对象
                    session = jsch.getSession(userName, host, port);
                    session.setPassword(password); // 设置密码
                    Properties config = new Properties();
                    config.put("StrictHostKeyChecking", "no");
                    session.setConfig(config); // 为Session对象设置properties
                    int timeout = 60000000;
                    session.setTimeout(timeout); // 设置timeout时间
                    session.connect(); // 通过Session建立链接
                    ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
                    channelExec.setCommand(cmd);
                    channelExec.setInputStream(null);
                    channelExec.setErrStream(System.err);
                    channelExec.connect();
                    InputStream in = channelExec.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
                    String buf;
                    StringBuilder sb = new StringBuilder();
                    while ((buf = reader.readLine()) != null) {
                        sb.append(buf);
                        System.out.println(buf);// 打印控制台输出
                    }
                    reader.close();
                    channelExec.disconnect();
                    session.disconnect();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

        }
        return to;
    }

    private boolean ls(String to) {
        //查询此rtmp是否已被转换
        //查询本地文件中有没有
        //有直接返回数据
        //没有执行转换延迟十五秒
        File dir = new File("/");
        boolean bl = false;
        try {
            String res = CommandUtil.run("ls /tmp/live", dir);
            System.out.println(res);
            String[] re = res.split("\n");
            for (String s : re) {
                String[] r = s.split("\\.");
                for (int j = 0; j < r.length; j++) {
                    if ("m3u8".equals(r[j])) {
                        if (r[j - 1].equals(to)) {
                            bl = true;
                            break;
                        }
                    }
                }
                if (bl) {
                    break;
                }
            }
            System.out.println(res);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bl;
    }
}
